<template>
	<div class="centered-container">
		<div class="card">
			<h2>创建角色</h2>

			<div class="bpublic">
				<PublicButton class="bpublic-button" @update-bPublic="updateBPublic" />
			</div>

			<div class="subcard">
				<div class="card-header">名称
					<div class="card-body">
						<input v-model="cname" type="text" placeholder="请输入名称" class="cname">
					</div>
				</div>
				<div class="card-header">语录
					<div class="card-body">
						<div class="select">
							<select v-model="mode">
								<option value="text">直接输入文本</option>
								<option value="file">上传文本文件</option>
							</select>
						</div>
						<div v-if="mode === 'text'" class="input">
							<textarea v-model="textContent" placeholder="输入角色的语录，给我们更多灵感吧！例如：“你干嘛~哎哟”。较长文本可以通过上传文件来分享哦~"></textarea>
						</div>
						<div v-else class="upload">
							<input type="file" class="txt" accept=".txt" @change="handleTextUpload">
						</div>
					</div>
				</div>
				<div class="card-header">语音
					<div class="card-body">
						<input type="file" class="mp3" accept=".mp3,.wav,.m4a" @change="handleVoiceUpload">
					</div>
				</div>
				<div class="card-header">形象
					<div class="card-body">
						<input type="file" class="jpg" accept=".jpg,.png,.mp4" @change="handleImageUpload">
					</div>
				</div>

				<div class="card-footer">
					<button class="confirm-button" @click="submitFiles" :class="{'disabled-button': bSubmitting}"
						:disabled="bSubmitting">确认创建 </button>
				</div>
			</div>
			<!-- 飘字提示信息 -->
			<MessageBox ref="messageBox" />
			<!-- 导航栏 -->
			<NavBar />
		</div>
	</div>
</template>


<script>
	import axios from 'axios';
	import NavBar from '../components/NavBar.vue';
	import MessageBox from '@/components/MessageBox.vue'
	import PublicButton from '../components/PublicButton.vue';
	import {
		postRequest,
		sendUploadSuccessMessage,
		getSign
	} from '@/api/url_query';
	import {
		uploadFile
	} from '@/utils/uploadFile';
	import {
		handleFileUpload,
		validateFileType
	} from '@/utils/fileHandler';
	import '@/utils/sdk.js';
	import {
		trackWebfunnyEvent
	} from '@/utils/pointID.js'



	export default {
		components: {
			NavBar,
			MessageBox,
			PublicButton
		},
		data() {
			return {
				bPublic: false, //默认私有
				cname: '',
				uid: '',
				cid: '',
				message: '',
				mode: 'text',
				textContent: '',
				textFile: null,
				voiceFile: null,
				imageFile: null,
				fileUploadInfo: {},
				voice_wav_url: '',
				voice_mp3_url: '',
				voice_m4a_url: '',
				picture_jpg_url: '',
				picture_mp4_url: '',
				text_url: '',
				bSubmitting: false
			};
		},

		mounted() {
			this.uid = localStorage.getItem('uid');
			trackWebfunnyEvent(198); // 进入创建角色界面
		},

		beforeDestroy() {
			trackWebfunnyEvent(199); // 离开创建角色界面
		},

		methods: {
			updateBPublic(value) {
				this.bPublic = value;
			},

			async getUploadUrls() {
				try {
					const {
						credentials,
						cid
					} = await getSign(this.uid, this.cname, this.bPublic);
					this.cid = cid;
					console.log('签名信息：', credentials);
					console.log('cid：', cid);
					console.log('bPublic：', this.bPublic);

					this.fileUploadInfo = {
						text: JSON.parse(credentials.text),
						voice_wav: JSON.parse(credentials.voice_wav),
						voice_mp3: JSON.parse(credentials.voice_mp3),
						voice_m4a: JSON.parse(credentials.voice_m4a),
						picture_jpg: JSON.parse(credentials.picture_jpg),
						picture_mp4: JSON.parse(credentials.picture_mp4)
					};
					return credentials;
				} catch (error) {
					console.error('获取签名失败：', error);
				}
			},


			handleTextUpload(event) {
				handleFileUpload(event, 'textFile', ['txt'], this);
			},

			handleVoiceUpload(event) {
				handleFileUpload(event, 'voiceFile', ['mp3', 'wav', 'm4a'], this);
			},

			handleImageUpload(event) {
				handleFileUpload(event, 'imageFile', ['jpg', 'png', 'mp4'], this);
			},

			async submitFiles() {
				trackWebfunnyEvent(200); // 点击创建按钮

				if (!this.cname) {
					this.$refs.messageBox.showMessage('请输入名称', 3000);
				} else if (!this.imageFile || (this.mode === 'file' && !this.textFile) || (this.mode === 'text' && !this
						.textContent)) {
					// 检查文件是否上传
					this.$refs.messageBox.showMessage('请确保输入文本或上传文本，选择了音频和图片', 3000);
				} else {
					// 如果前面的检查都通过，则执行后续操作
					this.bSubmitting = true;
					this.$refs.messageBox.showMessage('文件正在上传中，请稍后', 3000);


					await this.getUploadUrls(); // 在用户输入名称上传文件后获取签名信息

					if (this.mode === 'text') {
						try {
							const textBlob = new Blob([this.textContent], {
								type: 'text/plain'
							});
							const textUrl = await uploadFile(textBlob, this.fileUploadInfo);
							this.text_url = textUrl;
						} catch (error) {
							this.$refs.messageBox.showMessage('文本内容上传失败：' + error.message, 2000);
							throw error;
						}
					} else {
						try {
							const textUrl = await uploadFile(this.textFile, this.fileUploadInfo);
							this.text_url = textUrl;
						} catch (error) {
							this.$refs.messageBox.showMessage('文本文件上传失败：' + error.message, 2000);
							throw error;
						}
					}

					try {
						const voiceFileType = 'voice_' + this.voiceFile.type;
						const voiceUrl = await uploadFile(this.voiceFile, this.fileUploadInfo);
						this.voice_url = voiceUrl;
					} catch (error) {
						this.$refs.messageBox.showMessage('音频文件上传失败：' + error.message, 2000);
						throw error;
					}

					try {
						const imageFileType = 'picture_' + this.imageFile.type;
						const imageUrl = await uploadFile(this.imageFile, this.fileUploadInfo);
						this.picture_url = imageUrl;

						// 在所有文件上传成功后调用发送成功消息的函数
						await this.doSubmitFiles(this.bPublic);

					} catch (error) {
						console.error('图片文件上传失败：', error);
					}
				}
			},

			async doSubmitFiles() {
				try {
					await sendUploadSuccessMessage(this.uid, this.cid, this.bPublic)
					// 成功发送消息后显示成功的提示信息并跳转到首页
					this.$refs.messageBox.showMessage('恭喜您！ 智能伙伴已成功诞生！ 快来探索它的无限可能， 开启您的智能之旅吧', 2000, () => {
						this.$router.push('/homepage');
					});

				} catch (error) {
					console.error('发送消息失败：', error);
					this.$refs.messageBox.showMessage('创建失败', 2000);

				} finally {
					this.bSubmitting = false;
				}
			}
		}
	};
</script>

<style scoped>
	.card {
		position: relative;
		flex-direction: column;
		display: flex;
		width: 400px;
		border-radius: 8px;
		padding: 0px 15px 0px 15px;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
	}

	.card h2 {
		margin: 10px;
		text-align: center;
	}

	.subcard {
		width: 400px;
		border: 1px solid #ccc;
		border-radius: 8px;
		padding: 15px, 15px, 15px, 0;
		padding-top: 10px;
	}


	.card-header {
		padding: 15px;
		display: flex;
		margin-left: 45px;
	}

	.card-body {
		display: flex;
		flex-direction: column;
	}

	.card-body .cname {
		width: 100%;
		max-width: 300px;
		margin-left: 20px;
		box-sizing: border-box;
		/* 怪异盒模型 */
		padding: 7px;
	}


	.card-body .mp3 {
		width: 100%;
		max-width: 300px;
		margin-left: 20px;
		box-sizing: border-box;
	}

	.card-body .jpg {
		width: 100%;
		max-width: 300px;
		margin-left: 20px;
		box-sizing: border-box;
	}



	.card-footer {
		text-align: center;
	}

	.select,
	.input,
	.upload {
		margin-bottom: 10px;
		margin-left: 20px;
	}

	textarea {
		width: 170px;
		height: 100px;
		padding: 10px;
		border: 1px solid #ccc;
		border-radius: 5px;
	}

	.confirm-button {
		width: 100%;
		max-width: 300px;
		margin: 20px;
		background-color: rgb(52, 200, 252);
		color: #fff;
		border: none;
		border-radius: 8px;
		cursor: pointer;
		box-sizing: border-box;
		padding: 7px;
	}

	.confirm-button:hover {
		background-color: skyblue;
		border: none;
	}

	.disabled-button {
		background-color: skyblue;
		color: #fff;
	}

	.bpublic {
		display: flex;
		justify-content: flex-end;
	}
</style>